<script setup>
import {ref, onMounted} from 'vue';
// 引入添加用户的api
import {getDepartmentTreeApi, createUserApi} from '@/service/user.js';

const emit = defineEmits(['reload']);
const reload = () => {
  emit('reload');
}

// 加载用户树
const treeData = ref([]);
const fetchTreeData = () => {
  getDepartmentTreeApi().then(res => {
    treeData.value = res.data.tree;
  });
};

const drawerVisible = ref(false);
const ruleForm = ref({
  department_id: 0,
  nickname: '',
  realname: '',
  password: '',
  email: '',
  mobile: '',
  user_type: 1,
  status: 1,
  sort: 0
});

const rules = ref({
  department_id: [
    {required: true, message: '请选择部门', trigger: 'change'}
  ],
  nickname: [
    {required: true, message: '请输入昵称', trigger: 'blur'}
  ],
  realname: [
    {required: true, message: '请输入真实姓名', trigger: 'blur'}
  ],
  password: [
    {required: true, message: '请输入密码', trigger: 'blur'},
    {min: 6, message: '密码长度不能小于6位', trigger: 'blur'},
    {pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[^]{6,}$/, message: '密码必须包含大小写字母和数字', trigger: 'blur'}
  ],
  email: [
    {required: true, message: '请输入邮箱', trigger: 'blur'}
  ],
  mobile: [
    {required: true, message: '请输入手机号', trigger: 'blur'}
  ]
});

// 初始化form
const initForm = () => {
  ruleForm.value = Object.assign({}, {
    department_id: 0,
    nickname: '',
    realname: '',
    password: '',
    email: '',
    mobile: '',
    user_type: 1,
    status: 1,
    sort: 0
  });
}


// 提交数据
const ruleFormRef = ref(null);
const handleSave = () => {
  // 验证并提交数据
  ruleFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        createUserApi(ruleForm.value).then((res) => {
          if (res.code === 200) {
            ElMessage.success(res.msg);
            reload();
            closeDrawer();
          } else {
            ElMessage.error(res.msg);
          }
        });
      } catch (e) {
        ElMessage.error(e.message);
      }
    }
  });
};

// 打开抽屉
const openDrawer = () => {
  drawerVisible.value = true;
  fetchTreeData();
  initForm();
};

// 关闭抽屉
const closeDrawer = () => {
  drawerVisible.value = false;
  initForm();
};

defineExpose({
  openDrawer,
  closeDrawer
});

onMounted(() => {
  console.log('onMounted');
});
</script>

<template>
  <el-drawer v-model="drawerVisible" size="30%" title="添加用户" :close-on-click-modal="false">
    <el-form :model="ruleForm" :rules="rules" ref="ruleFormRef" label-width="100px" label-position="top">
      <el-form-item label="部门" prop="parent_id">
        <el-cascader v-model="ruleForm.department_id" :options="treeData"
                     :props="{label:'label', value:'id' ,checkStrictly: true, emitPath: false }" placeholder="请选择部门"
                     style="width:100%"></el-cascader>
      </el-form-item>
      <el-form-item label="昵称" prop="nickname">
        <el-input v-model="ruleForm.nickname" placeholder="请输入昵称"></el-input>
      </el-form-item>
      <el-form-item label="真实姓名" prop="realname">
        <el-input v-model="ruleForm.realname" placeholder="请输入真实姓名"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="ruleForm.password" placeholder="请输入密码" show-password></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="ruleForm.email" placeholder="请输入邮箱"></el-input>
      </el-form-item>
      <el-form-item label="手机号" prop="mobile">
        <el-input v-model="ruleForm.mobile" placeholder="请输入手机号"></el-input>
      </el-form-item>

      <el-form-item label="用户类型" prop="user_type">
        <el-radio-group v-model="ruleForm.user_type">
          <el-radio :value="1">普通用户</el-radio>
          <el-radio :value="2">管理者</el-radio>
          <el-radio :value="3">外部用户</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="ruleForm.status">
          <el-radio :value="1">启用</el-radio>
          <el-radio :value="0">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input-number v-model="ruleForm.sort" controls-position="right" :min="0" :max="9999"></el-input-number>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="handleSave">提交</el-button>
        <el-button @click="closeDrawer">取消</el-button>
      </el-form-item>
    </el-form>
  </el-drawer>
</template>

<style scoped lang="less">
.grid-icons {
  display: grid;
  grid-template-columns: repeat(8, 1fr);
  max-width: calc(100vw / 2);
  max-height: calc(100vh / 2);
  overflow: auto;

  .grid-icon {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 10px;
  }
}
</style>
